package br.com.casablanca.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import br.com.casablanca.dto.CondominioDTO;
import br.com.casablanca.utils.HibernateUtility;

public class CondominioDAO {

	@SuppressWarnings("unchecked")
	public  List<CondominioDTO> listar() throws Exception{
		List<CondominioDTO> lista = null;
		Session sessao = HibernateUtility.getSession();
		try {
			Query query = sessao.createQuery(" from CondominioDTO ");		
			lista = query.list();			
		} catch (Exception e) {			
			throw e;
		} finally {
			sessao.close();
		}
		return lista;
	}
	
	public  void incluir(CondominioDTO condominio) throws Exception{
		Transaction tx = null;
		Session sessao = HibernateUtility.getSession();
		try {			
			tx = sessao.beginTransaction();
			sessao.save(condominio);
			tx.commit();
		} catch (Exception e) {
			tx.rollback();
			sessao.close();
			throw e;
		}finally{
			sessao.close();	
		}
	}
	
	public  void alterar(CondominioDTO condominio) throws Exception{
		Transaction tx = null;
		Session sessao = HibernateUtility.getSession();
		try {			
			tx = sessao.beginTransaction();
			sessao.update(condominio);
			tx.commit();
		} catch (Exception e) {
			tx.rollback();
			sessao.close();
			throw e;
		}finally{
			sessao.close();	
		}
	}

	public void excluir(CondominioDTO condominio) throws Exception{
		Transaction tx = null;
		Session sessao = HibernateUtility.getSession();
		try {			
			tx = sessao.beginTransaction();
			sessao.delete(condominio);
			tx.commit();
		} catch (Exception e) {
			tx.rollback();
			sessao.close();
			throw e;
		}finally{
			sessao.close();	
		}
	}

	public  CondominioDTO consultar(String cnpj) throws Exception{
		CondominioDTO condominio = null;
		Session sessao = HibernateUtility.getSession();
		try {
			StringBuffer sql = new StringBuffer("");
			sql.append("from CondominioDTO cli where cli.cnpj =:cnpj");
				
			Query query = sessao.createQuery(sql.toString());		
			query.setString("cnpj", cnpj);
			condominio = (CondominioDTO) query.uniqueResult();			
		} catch (Exception e) {			
			throw e;
		} finally {
			sessao.close();
		}
		return condominio;		
	}
	
	public CondominioDTO pesquisarPorId(Long id) throws Exception{
		Session sessao = HibernateUtility.getSession();
		try {
			CondominioDTO temp = (CondominioDTO) sessao.get(CondominioDTO.class, id);
			return temp;
		} catch (Exception e) {			
			throw e;
		} finally {
			sessao.close();
		}
	}
}
